import axios from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Session } from '/@/utils/storage';

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_SERVER_URL as any,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' }
});

//打开加载层
const openLoading = () => {
	if((window.loading == undefined || window.loading == false)){
		const elLoading = ElLoading.service({
			lock: true,
			text: '正在努力加载中,请稍候...',
			background: 'rgba(0, 0, 0, 0.5)'
		});
		window.loading = true;
		window.elLoading = elLoading;
	}
}

//关闭加载层
const closeLoading = () => {
	setTimeout(() => {
		if(window.loading == true && window.elLoading != undefined){
			if(typeof window.elLoading.close == 'function'){
				window.elLoading.close();
			}
			window.loading = false;
			window.elLoading = undefined;
		}
	}, 2000);
}

//跳转到登录页面
const logout = (res: object) => {
	Session.clear();
	ElMessage.error(res.data.msg || 'Forbidden 服务端拒绝执行请求');
	ElMessageBox.alert('你已被登出，请重新登录', '提示', {'confirmButtonText' : '确定'}).then(() => {
		window.location.href = window.location.pathname;
	}).catch(() => {
	
	});
	setTimeout(() => {
		window.location.href = window.location.pathname;
	}, 10000);
}

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		if (Session.get('token')) {
			config.headers.common['Authorization'] = `Bearer ${Session.get('token')}`;
		}
		let method = 'post,put,delete';
		if(method.indexOf(config.method.toLowerCase()) != -1){
			openLoading();
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(res) => {
		closeLoading();
		if(res.status == 403){
			logout(res);
		}else if(res.data.code != 0 && res.data.code != 200 && res.config.responseType != 'blob'){
			ElMessage.error(res.data.msg || res.statusText);
			return res.data;
		}else{
			return res.data;
		}
	},
	(error) => {
		closeLoading();
		const res = error.response;
		if(res.status == 403){
			logout(res);
		}else{
			ElMessage.error(res.data.msg || res.statusText);
			return Promise.reject(error);
		}
	}
);

// 导出 axios 实例
export default service;
